<template>
  <div>
    <el-button @click="dialogFormVisible()"> 取消 </el-button>
    <el-dialog :visible.sync="dialogFormVisibles">
      <div>
        <el-row>
          <el-col :span="12"> <div id="container"></div></el-col>
          <el-col :span="12">
            lng:
            <input type="text" id="lng" />
            lat:
            <input type="text" id="lat" />
            地址
            <input type="text" id="add" />
            <div id="getLatAndLng"></div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import car from "@/assets/car.png"; //引入小车图标图片
export default {
  name: "contractPathManager",
  data() {
    return {
      dialogFormVisibles: false,
    };
  },
  mounted() {
    this.iniMap();
    this.getLatAndLng();
  },
  methods: {
    dialogFormVisible() {
      this.dialogFormVisibles = true;
      this.$nextTick(() => {
        this.iniMap();
        this.getLatAndLng();
      });
    },
    //https://jingyan.baidu.com/article/363872eccda8286e4aa16f4e.html 获取百度地图秘钥
    //引入百度js在  public/index.html引入
    //获取坐标可以参考https://lbsyun.baidu.com/jsdemo3.0.htm#js3_2
    iniMap() {
      //设置百度地图两点之间路线 参考 https://lbsyun.baidu.com/jsdemo.htm#sLngLatSearchPath
      var map = new BMap.Map("container"); //初始化地图
      //设置地图中心点 116.404, 39.915      11代表地图比例
      map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);

      //线路开始点
      var p1 = new BMap.Point(116.301934, 39.977552);
      //线路结束点
      var p2 = new BMap.Point(116.508328, 39.919141);

      //声明线路对象
      var driving = new BMap.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
      });
      //搜索两点之间的推荐线路
      driving.search(p1, p2);

      // 创建小车图标对象 car在上面有引入代码
      var carIcon = new BMap.Icon(car, new BMap.Size(52, 26));
      // 创建Marker标注，使用小车图标
      var pt = new BMap.Point(116.39662709149013, 39.992183926678415);
      var marker = new BMap.Marker(pt, {
        icon: carIcon,
      });
      // 将标注添加到地图
      map.addOverlay(marker);
    },
    getLatAndLng() {
      //获取经纬度
      console.log("地图");
      var map = new BMap.Map("getLatAndLng");
      map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
      map.enableScrollWheelZoom(true);
      var geocoder = new BMap.Geocoder();
      map.addEventListener("click", function (e) {
        document.getElementById("lng").value = e.point.lng;
        document.getElementById("lat").value = e.point.lat;
        geocoder.getLocation(e.point, function (rs) {
          var addComp = rs.addressComponents;
          var address =
            addComp.province +
            addComp.city +
            addComp.district +
            addComp.street +
            addComp.streetNumber;
          document.getElementById("add").value = address;
        });
      });
    },
  },
};
</script>
 <style type="text/css">
#container {
  width: 350px;
  height: 500px;
}
#getLatAndLng {
  width: 350px;
  height: 500px;
}
</style>